<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

/**
 * Class RunGamePrize
 * @package App
 */
class RunGamePrize extends Model
{
    public $timestamps = false;
    protected $table = "run_game_prize";

    const STATUS_WAITTING = 1;
    const STATUS_SHIPPING = 2;
    const STATUS_SENDING = 3;
    const STATUS_RECEIVED = 4;


    const HAS_PRICE_NO = 0;
    const HAS_PRICE_YES = 1;

    /**
     * 是否有未领取的该奖品
     * @param $user_id
     * @param $reward_id
     * @return mixed
     */
    static function IsReceived($user_id, $reward_id)
    {
        return intval(RunGamePrize::where('user_id', $user_id)->where('reward_id', $reward_id)->where('status', self::STATUS_WAITTING)->value('id'));
    }

    /**
     * 领取奖品
     * @param $price_id
     * @return array
     */
    static function AcceptPrice($price_id)
    {
        $price = RunGamePrize::find($price_id);
        $price->status = self::STATUS_SHIPPING;
        $price->name = request('name');
        $price->mobile = request('mobile');
        $price->province = request('province');
        $price->city = request('city');
        $price->county = request('county');
        $price->address = request('address');
        $price->updated_at = time();
        if (!$price->save()) {
            return error('领取失败');
        }

        $message = '领取成功';
        return success(compact('message'));
    }


    /**
     * 是否有未领取的奖励
     * @param $user_id
     * @return array
     */
    static function HasPrice($user_id)
    {
        $price_limit = DB::table('run_game_config')->value('price_limit') * 24 * 3600;
        $price = RunGamePrize::select('id', 'reward_id')->where('user_id', $user_id)->where('status', RunGamePrize::STATUS_WAITTING)->where('created_at','>=', time() - $price_limit)->first();
        //没待领取奖品
        if (!$price) {
            return ['has_price' => self::HAS_PRICE_NO];
        }

        //奖品详细信息
        $reward = RunGameReward::select('title', 'img', 'detail')->find($price->reward_id);
        return [
            'has_price' => self::HAS_PRICE_YES,
            'title' => $reward->title,
            'img' => $reward->img,
            'detail' => $reward->detail,
            'price_id' =>$price->id,
        ];
    }
}
